package com.cszy.yydqbfq.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.airbnb.lottie.LottieDrawable
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.adapter.IndexListAdapter
import com.cszy.yydqbfq.base.BaseVMActivity
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.PlaylistRepository
import com.cszy.yydqbfq.databinding.ActivityMusicListBinding
import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.viewmodel.IndexViewModel
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MusicListActivity : BaseVMActivity<IndexViewModel, ActivityMusicListBinding>(),
    IAdViewListener {
    private var category: String? = null
    private var listAdapter: IndexListAdapter? = null
    private var newGromoreFeedAd: NewGroMoreFeedAdManager? = null
    var type_proces: String? = null //功能入口类型
    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.init(this)

    }

    override fun initData() {
        type_proces = "第一次插屏"
        AdManager.loadChapin_nocache(
            this,
            21,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    newGromoreFeedAd = NewGroMoreFeedAdManager(
                        this@MusicListActivity,
                        BaseAdConstants.FEEDAD_Id,
                        mBinding?.frameLayoutBanner,
                        22
                    )
                    newGromoreFeedAd?.loadAd()
                }
            })


        category = intent?.extras?.getString("category")
        if (category == "金曲榜") {
            mViewModel.queryMusic()
        } else if (category == "本地音乐") {
            //showLoading("正在加载音频列表...")
            mBinding.lottieView.visibility = View.VISIBLE
            mBinding.lottieView.repeatCount = LottieDrawable.INFINITE // 无限循环
            mBinding.lottieView.playAnimation()
            loadAudioList()
        } else {
            mViewModel.queryMusicByCategory(category.toString())
        }
        when (category) {
            "金曲榜" -> {
                mBinding.headTitle.headCenterTitle.text = "金曲榜单"
            }

            "流行" -> {
                mBinding.headTitle.headCenterTitle.text = "每日推荐"
            }

            "怀旧" -> {
                mBinding.headTitle.headCenterTitle.text = "怀旧歌曲"
            }

            "摇滚" -> {
                mBinding.headTitle.headCenterTitle.text = "摇滚歌曲"
            }

            "民谣" -> {
                mBinding.headTitle.headCenterTitle.text = "民谣歌曲"
            }

            "说唱" -> {
                mBinding.headTitle.headCenterTitle.text = "说唱歌曲"
            }

            "国风" -> {
                mBinding.headTitle.headCenterTitle.text = "猜你喜欢"
            }

            "本地音乐" -> {
                mBinding.headTitle.headCenterTitle.text = "本地音乐"
            }
        }

        mBinding.headTitle.headRightImg.setImageResource(R.mipmap.ic_import)
        mBinding.headTitle.headRightImg.imageTintList = resources.getColorStateList(R.color.black)
        mBinding.headTitle.headRightImg.visibility =
            if (category == "本地音乐") View.VISIBLE else View.GONE

        listAdapter = IndexListAdapter()
        mBinding.recyMusicList.layoutManager = LinearLayoutManager(this)
        mBinding.recyMusicList.adapter = listAdapter
    }

    override fun initListener() {
        //返回
        mBinding.headTitle.headBack.setOnClickListener {
            finish()
        }
        listAdapter?.setOnItemClickListener { adapter, view, position ->
            // 传递整个列表和当前点击位置
            var songList = mViewModel.convertToSongInfoList(adapter.items)
            val intent = Intent(this, PlayDetailActivity::class.java).apply {
                putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songList))
                putExtra("CURRENT_POSITION", position)
            }
            startActivity(intent)
        }

        // 需要传递控件 id加入歌单点击事件
        listAdapter?.addOnItemChildClickListener(R.id.tv_add_gedanlist) { adapter, view, position ->
            // toast("点了添加歌单")
            var song_item = adapter.items.get(position)
            // 将 MusicListBean 转换为 Song
            val song = Song().apply {
                title = song_item.name ?: ""
                artist = song_item.author ?: ""
                cover = song_item.imageUrl ?: ""
                uri = song_item.songUrl
                duration = 0
                songlistbean_id = 0
            }
            val repository = PlaylistRepository()
            var geDanList = repository.getAllPlaylists()
                .filter { it.name != "本地音乐" }  // 过滤条件
            BottomPopupWithGeDanRecycler(this, geDanList, song).show(mBinding.root)
        }

        mBinding.headTitle.headRightImg.setOnClickListener {
            loadAudioList()
        }

    }

    override fun initObserve() {
        //获取音频数据
        mViewModel.queryMusicResult.observe(this) { musiclist ->
            if (category == "金曲榜" && musiclist!!.isNotEmpty()) {
                // 获取前3条数据用于特殊UI展示
                val topThreeList = musiclist.take(3)
                val remainingList = musiclist.drop(3)

                handleTopThreeItems(topThreeList)

                // 剩余数据显示在列表中
                listAdapter?.submitList(remainingList as List<MusicListBean>?)
            } else {
                listAdapter?.submitList(musiclist as List<MusicListBean>?)
            }
        }
    }


    private fun handleTopThreeItems(topThreeList: List<MusicListBean?>) {
        val rankViewList = listOf(
            mBinding.topOneContent,
            mBinding.topTwoContent,
            mBinding.topThreeContent
        )

        // 更清晰的可见性控制
        mBinding.llRank.visibility = if (topThreeList.isNotEmpty()) View.VISIBLE else View.GONE

        // 使用 zip 同时遍历数据和视图，避免索引越界
        topThreeList.take(3).forEachIndexed { index, item ->
            if (index < rankViewList.size) {
                val rankView = rankViewList[index]
                item?.let {
                    rankView.tvAuthor.text = it.author
                    rankView.tvSongName.text = it.name
                    Glide.with(this)
                        .load(it.imageUrl)
                        .apply(
                            RequestOptions()
                                .transform(RoundedCorners(30))
                        )
                        .into(rankView.ivRecommendCover)
                }
            }
        }
    }


    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) // 平滑过渡
    }

    private fun loadAudioList() {
        // 1. 立即显示加载框（UI线程）
        //   showLoading("正在加载音频列表...")

        lifecycleScope.launch {
            try {
                // 2. 在IO线程执行数据库操作
                val audioList = withContext(Dispatchers.IO) {
                    delay(500)
                    mViewModel.getAudioInfoListSync()
                }

                // 3. 回到主线程更新UI
                withContext(Dispatchers.Main) {
                    val songInfoList = mViewModel.convertToMusicListBeanList(audioList)
                    listAdapter?.submitList(songInfoList)
                    mBinding.lottieView.cancelAnimation()
                    mBinding.lottieView.visibility = View.INVISIBLE
                    toast("加载完成")
                }

            } catch (e: Exception) {
                toast("加载失败: ${e.message ?: "未知错误"}")
                dismissLoading()
            } finally {
                // 4. 确保在主线程关闭加载框
                withContext(Dispatchers.Main) {
                    // dismissLoading()
                }
            }
        }
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        when (type_proces) {
            "第一次插屏" -> {
                newGromoreFeedAd = NewGroMoreFeedAdManager(
                    this,
                    BaseAdConstants.FEEDAD_Id,
                    mBinding?.frameLayoutBanner,
                    22
                )
                newGromoreFeedAd?.loadAd()
            }
        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

}

